var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var watchify = require('watchify');
var tsify = require('tsify');
var gutil = require('gulp-util');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var buffer = require('vinyl-buffer');
var paths = {
  pages: ['src/*.html']
};

var watchedBrowserify = watchify(browserify({ // 将browserify实例包裹在watchify的调用里，控制生成的结果。
  basedir: '.',
  debug: true,
  entries: ['src/main.ts'],
  cache: {},
  packageCache: {}
}).plugin(tsify)
.transform('babelify', {
  presets: ['es2015'],
  extensions: ['.ts']
}));

gulp.task('copy-html', function() {
  return gulp.src(paths.pages)
      .pipe(gulp.dest('dist'));
})

function bundle() {
  return watchedBrowserify
      .bundle()
      .pipe(source('bundle.js'))
      .pipe(buffer())
      .pipe(sourcemaps.init({loadMaps: true}))
      // .pipe(uglify())
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('dist'));
}

gulp.task('default', ['copy-html'], bundle);
watchedBrowserify.on('update', bundle); // 每次TypeScript文件改变时Browserify会执行bundle函数
watchedBrowserify.on('log', gutil.log); // 将日志打印到控制台。
